package org.willa.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.willa.business.sys.entity.SysUser;
import org.willa.common.enums.DateTypeEnum;
import org.willa.common.util.ConverToUtils;
import org.willa.common.util.DateUtils;
import org.willa.common.util.PasswordUtils;
import org.willa.common.vo.Result;
import org.willa.system.entity.vo.SysUserVO;
import org.willa.system.mapper.SysUserMapper;
import org.willa.system.service.ISysUserService;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author wuwei
 * @date 2024/1/5
 * @apiNote
 */
@Slf4j
@Service
public class SysUserServiceImpl implements ISysUserService {

    private final int defaultPwdUpdateTimeLength = 90;
    private Map<String, Object> sysUserDefaultValueMap = new HashMap<String, Object>() {{
        // 性别(0-默认未知,1-男,2-女)
        put("sex", 0);
        // 生日
        put("birthday", new Date());
        // 状态(1-正常,2-冻结)
        put("status", 2);
        // 删除状态(0-正常,1-已删除)
        put("del_flag", 0);
        // 密码更新时间
        put("pwd_update", DateUtils.getDate(DateTypeEnum.DATE, defaultPwdUpdateTimeLength));
    }};

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    @Transactional()
    public Result insertUser(SysUserVO sysUserVo) {
        // 生成md5密码盐
        sysUserVo.setPassword(PasswordUtils.encrypt(sysUserVo.getPassword()));
        // vo对象转换
        SysUser sysUser = ConverToUtils.convertVoToEntity(
                new SysUser(), sysUserVo,
                Arrays.asList("roleList"),
                sysUserDefaultValueMap);


        // 创建系统用户
        if (sysUserMapper.insert(sysUser) > 0 && !Objects.isNull(sysUserVo.getRoleList())) {
            // 增加 系统用户权限
            // TODO:新增用户-增加系统用户全新未实现 待前台上线后进行调整
        }

        //

        return Result.ok();
    }
}
